package me.keiwu.user.controller;

import me.keiwu.pub.data.wx.WXUserInfoData;
import me.keiwu.pub.service.WXService;
import me.keiwu.user.service.UserService;
import me.keiwu.pub.data.Response;
import me.keiwu.pub.data.wx.WXSessionData;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by kei on 20/10/2017.
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);


    @Autowired
    private WXService wxService;
    @Autowired
    private UserService userService;


    @RequestMapping("")
    public Response login(String encryptedData, String code, String iv, String channel) {
        logger.info("login encryptedData_is_null={}, code={}, iv={}, channel={}", encryptedData == null, code, iv, channel);
        WXSessionData data = wxService.getSession(code);
        if (data == null || StringUtils.isBlank(data.getSessionKey())) return Response.fail("登录失败");
        WXUserInfoData userInfo = wxService.decryptData(encryptedData, iv, data.getSessionKey(), WXUserInfoData.class);
        logger.info("request login userInfo = {}", userInfo);
        return userService.login(userInfo, data, channel);
    }

}
